package handler

import (
	"app-master/cache"
	"app-master/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func UpAdd(c *gin.Context) {
	id := c.PostForm("id")
	var app model.App
	model.DB.Model(&app).Where("id=?", id).Update("up_num", gorm.Expr("up_num+?", 1))
	redis_key := "up_add_" + id
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "下载成功",
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var app model.App
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).First(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
	return
}

func List(c *gin.Context) {
	var types []model.Type
	model.DB.Find(&types)
	redis_key := "type_list"
	jsonData, _ := json.Marshal(types)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": types,
	})
	return
}

func TypeList(c *gin.Context) {
	app_id := c.Query("app_id")
	var types model.Type
	model.DB.Table("types").
		Joins("JOIN type_apps ON types.id = type_apps.type_id").
		Where("app_id=?", app_id).Find(&types)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": types,
	})
	return
}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	type_id, _ := strconv.Atoi(c.PostForm("type_id"))
	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "发布失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	if name == "" || type_id == 0 {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空,类别不能为0",
		})
		return
	}
	data := model.App{
		Name:   name,
		TypeId: type_id,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	var app model.App
	redis_key := "app_" + name
	model.DB.Where("name=?", name).First(&app)
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
